{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 82,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0]: 9:1次\n",
      "[1]: 17:1次\n",
      "[2]: 3:1次\n",
      "[3]: 5:1次\n",
      "[4]: 5:2次\n",
      "[5]: 16:1次\n",
      "[6]: 16:2次\n",
      "[7]: 20:1次\n",
      "[8]: 6:1次\n",
      "[9]: 2:1次\n",
      "[10]: 13:1次\n",
      "[11]: 19:1次\n",
      "[12]: 3:2次\n",
      "[13]: 13:2次\n",
      "[14]: 18:1次\n",
      "[15]: 20:2次\n",
      "[16]: 10:1次\n",
      "[17]: 5:3次\n",
      "[18]: 9:2次\n",
      "[19]: 5:4次\n",
      "[20]: 16:3次\n",
      "[21]: 9:3次\n",
      "[22]: 5:5次\n",
      "[23]: 10:2次\n",
      "[24]: 15:1次\n",
      "[25]: 11:1次\n",
      "[26]: 9:4次\n",
      "[27]: 8:1次\n",
      "[28]: 16:4次\n",
      "[29]: 5:6次\n",
      "==================================\n",
      "[5]出现次数:6\n",
      "[9, 16]出现次数:4\n",
      "[3, 20, 13, 10]出现次数:2\n"
     ]
    }
   ],
   "source": [
    "#题目：随机生成20个[1,20]的正整数,统计每个数字出现的次数，排序并降序输出次数最多的前三个数字和次数\n",
    "\n",
    "import random\n",
    "d = dict()\n",
    "m1,m2,m3 = 1, 1 ,1\n",
    "## 生成20个随机正整数，并把正整数和出现的次数存到字典d\n",
    "## 并通过比较得出次数最多的top3: m1~m3\n",
    "for i in range(30):\n",
    "    n = random.randint(1,20)\n",
    "    if d.get(n) is None: # 这里也可以改成if n not in d\n",
    "        d[n] = 1\n",
    "    else:\n",
    "        d[n] += 1\n",
    "    print(\"[{}]: {}:{}{}\".format(i,n,d[n],'次'))\n",
    "    if d[n] >= m1: \n",
    "        m1 =d[n]\n",
    "    elif d[n] >= m2:\n",
    "        m2 =d[n]\n",
    "    elif d[n] >= m3:\n",
    "        m3 =d[n]\n",
    "    else:\n",
    "        continue\n",
    "## 由于出现m1,m2,m3次数的正整数有可能有多个，因此将其分别存到列表l1~l3,并打印\n",
    "l1,l2,l3 = [],[],[]\n",
    "for k in d:\n",
    "    if d[k] == m1:\n",
    "        l1.append(k)      \n",
    "    elif d[k] == m2:\n",
    "        l2.append(k)\n",
    "    elif d[k] == m3:\n",
    "        l3.append(k)\n",
    "    else:\n",
    "        continue\n",
    "print('==================================')\n",
    "print(\"{}{}:{}\".format(l1,'出现次数',m1))\n",
    "print(\"{}{}:{}\".format(l2,'出现次数',m2))\n",
    "print(\"{}{}:{}\".format(l3,'出现次数',m3))\n",
    "\n",
    "\n",
    "# 这里做的不错"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
